package info.amber.vboot.jms;

import info.amber.vboot.json.JacksonKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import java.util.Map;

@Component
public class JmsService {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @JmsListener(destination = ActiveMQConfig.QUEUE_DEMO)
    @SendTo("queue.out")
    public String onMessage(Message message, Map map) throws JMSException {

        System.out.println("queue.demo ------------- ");
        System.out.println(JacksonKit.bean2json(message));
        System.out.println(JacksonKit.bean2json(map));
        System.out.println(message.getClass().getName());
        System.out.println(map.get("data"));
        Object data = null;
        if (message instanceof MapMessage) {
            MapMessage msg = (MapMessage) message;
            data = msg.getObject("data");
            System.out.println(data);

        }
        System.out.println("queue.demo done------- ");
        return String.valueOf(data);
    }

    @JmsListener(destination = "queue.out")
    public void out(String text) {

        System.out.println("queue.out:"+text);
    }

    public void send(Map map) {
        jmsMessagingTemplate.convertAndSend(ActiveMQConfig.QUEUE_DEMO, map);
    }
}
